<?php

namespace App\Console\Commands;

use Aliyun\AliSms;
use App\Api\Controllers\Config\VbillConfigController;
use App\Models\SmsConfig;
use App\Models\StorePayWay;
use App\Models\VbillaStore;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VbillaStoreAudit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vbilla-audit';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'vbilla-audit';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        try {
            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("vbill_stores");
            } else {
                $obj = DB::table('vbilla_stores');
            }
            $JdStoreItem = $obj->where('taskStatus', 0)->get()->toArray();

            foreach ($JdStoreItem as $k => $v) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbilla_config($v->config_id);
                if (!$vbill_config) {
                    continue;
                }

                if (!$v->applicationId) {
                    continue;
                }

                $obj = new \App\Api\Controllers\Vbill\BaseController();
                $url = $obj->open_query_store_url;
                $data = [
                    'orgId' => $vbill_config->orgId,
                    'reqId' => time(),
                    'version' => '1.0',
                    'timestamp' => date('Ymdhis', time()),
                    'signType' => 'RSA',
                    'reqData' => [
                        'applicationId' => $v->applicationId,
                    ],
                ];

                $re = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);

                //系统错误
                if ($re['status'] == 0) {
                    continue;
                }

                //业务成功
                if ($re['data']['code'] == "0000") {

                    //失败
                    if ($re['data']['respData']['bizCode'] == "0001") {
                        $data_up = [
                            'status' => 3,
                            'status_desc' => $re['data']['respData']['bizMsg'],
                        ];
                        StorePayWay::where('store_id', $v->store_id)
                            ->where('company', 'vbilla')
                            ->update($data_up);
                    }


                    if (!isset($re['data']['respData']['taskStatus'])) {
                        continue;
                    }

                    //审核成功
                    if ($re['data']['respData']['taskStatus'] == "1") {
                        $data_up = [
                            'status' => 1,
                            'status_desc' => '审核成功',
                        ];
                        StorePayWay::where('store_id', $v->store_id)
                            ->where('company', 'vbilla')
                            ->update($data_up);

                        $in_data = [
                            'taskStatus' => $re['data']['respData']['taskStatus'],
                        ];
                        VbillaStore::where('id', $v->id)->update($in_data);

                        $childNo = "";
                        foreach ($re['data']['respData']['repoInfo'] as $k1 => $v1) {
                            if ($v1['childNoType'] == "WX") {
                                $childNo = $v1['childNo'];
                            } else {
                                continue;
                            }
                        }

                        //报备微信授权目录
                        $url = $obj->weixin_config;
                        $data = [
                            'orgId' => $vbill_config->orgId,
                            'reqId' => time(),
                            'version' => '1.0',
                            'timestamp' => date('Ymdhis', time()),
                            'signType' => 'RSA',
                            'reqData' => [
                                'mno' => $v->mno,
                                'subMchId'=>$childNo,
                                'type'=>'03',
                                'jsapiPath'=>env('APP_URL') . '/api/vbill/weixin/'
                            ],
                        ];
                        $wx_auth_res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
                        Log::info('随行付A报备微信授权目录结果');
                        Log::info($wx_auth_res);

                        //随行付A--提交实名认证申请接口
                        $wx_submit_url = $obj->wechat_commit_apply;
                        $wx_submit_data = [
                            'orgId' => $vbill_config->orgId,
                            'reqId' => time(),
                            'version' => '1.0',
                            'timestamp' => date('Ymdhis', time()),
                            'signType' => 'RSA',
                            'reqData' => [
                                'mno' => $v->mno
                            ],
                        ];
                        $wx_submit_res = $obj->execute($wx_submit_data, $wx_submit_url, $vbill_config->privateKey, $vbill_config->sxfpublic);
                        Log::info('随行付A提交实名认证申请结果');
                        Log::info($wx_submit_res);
                    }

                    //审核失败
                    if ($re['data']['respData']['taskStatus'] == "2" || $re['data']['respData']['taskStatus'] == "3") {
                        $data_up = [
                            'status' => 3,
                            'status_desc' => $re['data']['respData']['suggestion'],
                        ];
                        StorePayWay::where('store_id', $v->store_id)
                            ->where('company', 'vbilla')
                            ->update($data_up);

                        $in_data = [
                            'taskStatus' => $re['data']['respData']['taskStatus'],
                        ];
                        VbillaStore::where('id', $v->id)->update($in_data);
                    }

                } else {
                    continue;
                }

            }

        } catch (\Exception $exception) {
            Log::info('随性付A同步门店状态报错');
            Log::info($exception);
        }
    }


    public function send($name, $status, $phone, $config_id = '1234')
    {
        try {
            $config = SmsConfig::where('type', '7')->where('config_id', $config_id)->first();
            if (!$config) {
                $config = SmsConfig::where('type', '7')->where('config_id', '1234')->first();
            }

            if ($config && $config->app_key && $phone) {
                $data = ["name" => $name, 'status' => $status];
                $this->sendSms($phone, $config->app_key, $config->app_secret, $config->SignName, $config->TemplateCode, $data);
            }
        } catch (\Exception $exception) {
        }
    }


    public function sendSms($phone, $app_key, $app_secret, $SignName, $TemplateCode, $data)
    {
        $demo = new AliSms($app_key, $app_secret);
        $response = $demo->sendSms(
            $SignName, // 短信签名
            $TemplateCode, // 短信模板编号
            $phone, // 短信接收者
            $data
        );
        return $response;

    }


}
